package at.irian.jsfatwork.broker.domain.client;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author Thomas Spiegl
 */
@Repository
public class ClientRepository {

    @PersistenceContext
    private EntityManager em;

    public Client getClientByUserName(String username) {
        Query query = em.createQuery("select c from Client c where c.userName=:username");
        query.setParameter("username", username);
        return (Client) query.getSingleResult();
    }

    @SuppressWarnings({"unchecked"})
    public List<Client> getAllClients() {
        Query query = em.createQuery("select c from Client c order by c.secondName, c.firstName ");
        return query.getResultList();
    }

    public Client createPersistentClient(String firstName, String secondName, String username) {
        Client client = new Client();
        client.setFirstName(firstName);
        client.setSecondName(secondName);
        client.setUserName(username);
        save(client);
        return client;
    }

    public Client createEmptyTransientClient() {
        return new Client();
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void save(Client client) {
        if (client.isTransient()) {
            em.persist(client);
        }
    }
        
    @Transactional(propagation = Propagation.MANDATORY)
    public void delete(Client client) {
        if (!client.isTransient()) {
            em.remove(client);
        }
    }
}
